#include "t_net_msg.h"
#include <stdlib.h>
#include <string.h>
#define DEAFULT_MSGLEN 4096
#define DEAFULT_HEADLEN 32

int t_net_msg_alloc(t_net_msg *msg)
{
    msg->data = (uint8_t *)calloc(1, DEAFULT_MSGLEN);
    if (!msg->data)
    {
        return -1;
    }

    msg->data_cap = DEAFULT_MSGLEN;
    msg->data_len = DEAFULT_MSGLEN;
    return 0;
}
//与vector类似
int t_net_msg_append(t_net_msg *msg, void *data, uint32_t len)
{
    if (msg->data_cap < len)
    {
        int new_cap = 0;
        if (len % DEAFULT_MSGLEN == 0)
        {
            new_cap = len;
        }
        else
        {
            new_cap = (len / DEAFULT_MSGLEN + 1) * DEAFULT_MSGLEN;
        }
        uint8_t *old = msg->data;
        msg->data = (uint8_t *)calloc(1, new_cap);
        if (!msg->data)
        {
            return -1;
        }
        free(old);
        msg->data_len = len;
        msg->data_cap = new_cap;
    }
    memcpy(msg->data, data, len);
    return 0;
}
int t_net_msg_head_alloc(t_net_msg *msg)
{
    msg->head = (uint8_t *)calloc(1, DEAFULT_HEADLEN);
    if (!msg->head)
    {
        return -1;
    }
    msg->head_len = DEAFULT_HEADLEN;
    msg->head_cap = DEAFULT_HEADLEN;
    return 0;
}
int t_net_msg_head_append(t_net_msg *msg, void *head_data, uint32_t len)
{
    if (msg->head_cap < len)
    {
        int new_cap = 0;
        if (len % DEAFULT_HEADLEN == 0)
        {
            new_cap = len;
        }
        else
        {
            new_cap = (len / DEAFULT_HEADLEN + 1) * DEAFULT_HEADLEN;
        }
        uint8_t *old = msg->head;
        msg->head = (uint8_t *)calloc(1, len);
        if (!msg->head)
        {
            return -1;
        }
        free(old);
        msg->head_len = len;
        msg->data_cap = new_cap;
    }
    memcpy(msg->head, head_data, len);
    return 0;
}
int t_net_recvmsg(int fd,t_net_msg *msg);
int t_net_sendmsg(int fd,t_net_msg *msg);